package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;

    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo")EmployeeQueryObject qo){
        /*System.out.println("角色.............."+ SecurityUtils.getSubject().hasRole("HR_MGR"));
        System.out.println("权限.............."+ SecurityUtils.getSubject().isPermitted("role:list"));*/
        List<Department> depts = departmentService.selectAll();
        model.addAttribute("depts",depts);
        model.addAttribute("pageResult",employeeService.query(qo));
        return "employee/list";
    }
    @RequestMapping("/delete")
    public String delete(Long id){
        if(id != null){
            employeeService.deleteByPrimaryKey(id);
            }
            return "redirect:/employee/list.do";
    }
    @RequestMapping("/input")
    public String input(Long id,Model model){
        List<Role> roles = roleService.selectAll();
        model.addAttribute("roles",roles);
        List<Department> departments = departmentService.selectAll();
        model.addAttribute("departments",departments);
        if(id != null){
            Employee employee = employeeService.selectByPrimaryKey(id);
            model.addAttribute("employee",employee);
        }
        return "employee/input";
    }
    @ResponseBody
    @RequestMapping("/saveOrUpdate")
    public JsonResult saveOrUpdate(Employee employee,Long[] ids){
            if(employee.getId()!=null){
                employeeService.updateByPrimaryKey(employee, ids);
            }else{
                employeeService.insert(employee, ids);
            }
        return new JsonResult();
    }

    @RequestMapping("/updatePwd")
    public String updatePwd(Long id, Model model, HttpSession session){
        String name = (String)SecurityUtils.getSubject().getPrincipal();
        Employee employee = employeeService.selectByName(name);
            model.addAttribute("employee",employee);
        return "employee/updatePwd";
    }
    @RequestMapping("/judge")
    @ResponseBody
    public JsonResult judge(String oldPassword, String newPassword, HttpSession session) {
        try{
            String name = (String)SecurityUtils.getSubject().getPrincipal();
            Employee employee = employeeService.selectByName(name);
            Long id = employee.getId();
            //对新老密码进行加密
            Md5Hash op = new Md5Hash(oldPassword, name);
            Md5Hash np = new Md5Hash(newPassword, name);
            employeeService.judge(op.toString(), np.toString(), id);
            return new JsonResult();
        }catch(Exception e){
            e.printStackTrace();
            return new JsonResult(false,"操作失败");
        }

    }

    @ResponseBody
    @RequestMapping("/batchDelete")
    public JsonResult batchDelete(Long[] ids){
        System.out.println(ids);
            if (ids != null){
                for (Long id:ids) {
                    employeeService.deleteByPrimaryKey(id);
                }
            }
            return new JsonResult();
    }

    /**
     * 插件要返回valid:false 或者valid:true
     * @param name
     * @return
     */
    @ResponseBody
    @RequestMapping("/checkName")
    public HashMap checkName(String name){
        HashMap map = new HashMap();
        Employee employee = employeeService.selectByName(name);
        map.put("valid",employee==null);
        return map;
    }

    @RequestMapping("/exportXls")//导入
    public void exportXls(HttpServletResponse response) throws Exception {
        //文件下载的响应头（让浏览器访问资源的的时候以下载的方式打开）
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
        //调用创建excel的方法
        Workbook wb = employeeService.exportXls();
        //把excel的数据输出给浏览器
        wb.write(response.getOutputStream());
    }

    @ResponseBody
    @RequestMapping("/importXls")//导入
    public JsonResult importXls(MultipartFile file) throws Exception {
        employeeService.importXls(file);
        return new JsonResult();
    }

}
